package com.unidt.www.module.third.workbar.service.impl;

import com.alibaba.fastjson.JSON;
import com.unidt.www.framework.common.exception.ServiceException;
import com.unidt.www.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.unidt.www.module.system.controller.admin.auth.vo.AuthLoginReqVO;
import com.unidt.www.module.system.controller.admin.auth.vo.AuthLoginRespVO;
import com.unidt.www.module.system.controller.admin.user.vo.user.UserCreateReqVO;
import com.unidt.www.module.system.dal.dataobject.dept.DeptDO;
import com.unidt.www.module.system.dal.dataobject.permission.UserRoleDO;
import com.unidt.www.module.system.dal.dataobject.user.AdminUserDO;
import com.unidt.www.module.system.dal.dataobject.user.SystemZzdUser;
import com.unidt.www.module.system.dal.mysql.dept.DeptMapper;
import com.unidt.www.module.system.dal.mysql.permission.UserRoleMapper;
import com.unidt.www.module.system.dal.mysql.user.AdminUserMapper;
import com.unidt.www.module.system.dal.mysql.user.SystemZzdUserMapper;
import com.unidt.www.module.system.service.auth.AdminAuthService;
import com.unidt.www.module.system.service.user.AdminUserService;
import com.unidt.www.module.third.workbar.app.WorkBarUtils;
import com.unidt.www.module.third.workbar.service.IWorkBarLoginService;
import com.unidt.www.module.third.workbar.vo.AccessToken;
import com.unidt.www.module.third.workbar.vo.WorkBarDept;
import com.unidt.www.module.third.workbar.vo.WorkBarUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author sk
 * @Description:
 * @Date 2022/11/28 16:22
 **/
@Service
@Slf4j
public class WorkBarLoginServiceImpl implements IWorkBarLoginService {

    @Resource
    private AdminUserMapper userMapper;
    @Resource
    SystemZzdUserMapper systemZzdUserMapper;

    @Resource
    private AdminAuthService authService;

    @Resource
    AdminUserService adminUserService;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Resource
    WorkBarUtils workBarUtils;

    @Resource
    DeptMapper deptMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AuthLoginRespVO loginByCode(String code) {

        if (StringUtils.isBlank(code)) {
            throw new ServiceException(GlobalErrorCodeConstants.UNKNOWN.getCode(), "用户信息code失败");

        }
        log.info("工作台免登陆 code:{}", code);
        AccessToken accessTokenVo = workBarUtils.getAccessToken();
        log.info("工作台获取token accessTokenVo:{}", accessTokenVo.getAccessToken());
        WorkBarUser userVo = workBarUtils.getUserByCode(accessTokenVo, code);


        if (Objects.isNull(userVo)) {
            throw new ServiceException(GlobalErrorCodeConstants.UNKNOWN.getCode(), "用户不存在");
        } else {
            log.info("工作台获取用户信息 :{}", JSON.toJSONString(userVo));

            /**
             * 根据浙浙政钉id 获取用户信息
             */
            String zzdId = userVo.getZzdId();

            if (StringUtils.isBlank(zzdId)) {
                throw new ServiceException(GlobalErrorCodeConstants.UNKNOWN.getCode(), "账号异常");
            }

            SystemZzdUser zzdUser = systemZzdUserMapper.getByZzdId(zzdId);
            if (Objects.nonNull(zzdUser)) {

                AdminUserDO adminUserDO = userMapper.selectById(zzdUser.getUserId());
                log.info("流程引擎用户信息 :{}", JSON.toJSONString(adminUserDO));

                String userName = adminUserDO.getUsername();
                AuthLoginRespVO mAuthLogin = authService.loginNoPassWord(new AuthLoginReqVO()
                        .setUsername(userName)
                );
                return mAuthLogin;
            } else {

                /**
                 * 插入zzdUser
                 * 用zzdId作为登录名
                 */
                registerAccount(userVo);
                AuthLoginRespVO mAuthLogin = authService.loginNoPassWord(new AuthLoginReqVO()
                        .setUsername(zzdId)
                );
                return mAuthLogin;

            }
        }
    }


    /**
     * 注册
     *
     * @param userVo
     */
    private void registerAccount(WorkBarUser userVo) {

        UserCreateReqVO mUserCreateReqVO = new UserCreateReqVO();
        mUserCreateReqVO.setMobile(userVo.getMobile());
        mUserCreateReqVO.setUsername(userVo.getZzdId());
        mUserCreateReqVO.setNickname(userVo.getName());
        mUserCreateReqVO.setPassword("Qq123456");
        mUserCreateReqVO.setUserType(1);
        mUserCreateReqVO.setTenantId(1L);


        List<WorkBarDept> depts = userVo.getBelongUnits();

        if (!depts.isEmpty()) {
            List<String> thirdDeptIds = depts.stream().map(d -> d.getId()).collect(Collectors.toList());

            /**
             * 取其中的一个部门
             */
            String thirdDeptId = thirdDeptIds.get(0);

            DeptDO deptDO = deptMapper.getByThirdId(thirdDeptId);
            if (Objects.nonNull(deptDO)) {
                mUserCreateReqVO.setDeptId(deptDO.getId());
            }
        }
        Long userId = adminUserService.createUser(mUserCreateReqVO);

        /**
         *  查找系统对应部门
         */

        SystemZzdUser zzdUser = new SystemZzdUser();
        zzdUser.setZzdId(userVo.getZzdId());
        zzdUser.setUserId(userId);
        zzdUser.setZzdCode(userVo.getZzdCode());
        this.systemZzdUserMapper.insert(zzdUser);

        /**
         * 添加权限
         */
        UserRoleDO userRoleDO = new UserRoleDO();
        userRoleDO.setUserId(userId);
        userRoleDO.setRoleId(114L);

        this.userRoleMapper.insert(userRoleDO);

    }

}
